// Keywords: identity by state, uniquing, unique down, back mutation, two alleles

// biallelicFrequencies() is used by the LogFile
function (float)biallelicFrequencies(void) {
	g = NULL;
	for (ind in p1.individuals)
		g = rbind(g, ind.getValue('G1'), ind.getValue('G2'));
	f = apply(g, 1, "mean(applyValue);");
	return f;
}

initialize() {
	defineConstant("MU", 1e-4);
	defineConstant("L", 100);
}
1 early() {
	sim.addSubpop("p1", 100);
	
	// all individuals start in the "wild-type" state
	// genomic state is kept in two vectors, G1 and G2
	p1.individuals.setValue("G1", rep(F, L));
	p1.individuals.setValue("G2", rep(F, L));
	
	// log results
	log = community.createLogFile("freq.csv", logInterval=10);
	log.addTick();
	log.addMeanSDColumns("freq", "biallelicFrequencies();");
}
modifyChild() {
	// inherit biallelic loci from parents with recombination and mutation
	parentG1 = parent1.getValue("G1");
	parentG2 = parent1.getValue("G2");
	recombined = ifelse(rbinom(L, 1, 0.5) == 0, parentG1, parentG2);
	mutated = ifelse(rbinom(L, 1, MU) == 1, !recombined, recombined);
	child.setValue("G1", mutated);
	
	parentG1 = parent2.getValue("G1");
	parentG2 = parent2.getValue("G2");
	recombined = ifelse(rbinom(L, 1, 0.5) == 0, parentG1, parentG2);
	mutated = ifelse(rbinom(L, 1, MU) == 1, !recombined, recombined);
	child.setValue("G2", mutated);
	
	return T;
}
50000 late() { }
